package com.shimao.celnet.payment.quartz;

import com.alibaba.fastjson.JSON;

import com.shimao.celnet.payment.controller.apinotcheck.CallOut_invOpenRetInfoOutController;
import com.shimao.celnet.payment.controller.apinotcheck.CallOut_invPdfOutController;
import com.shimao.celnet.payment.controller.apinotcheck.CallOut_invoiceQueryOutController;
import com.shimao.celnet.payment.form.IAppInterfaceForm;
import com.shimao.celnet.payment.model.PInvoiceBlue;
import com.shimao.celnet.payment.service.IAppInterfaceService;
import com.shimao.celnet.payment.service.PInvoiceBlueService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.GetJFSystemToken;
import com.shimao.celnet.payment.util.HttpSendPostUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;



import java.util.List;

/**推送所有已经开出的电子票
 * Created by XSW on 2018/9/4.
 */
public class EInvoicePush implements Job {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private IAppInterfaceService iAppInterfaceService;

    @Autowired
    private PInvoiceBlueService pInvoiceBlueService;

    @Autowired
    private GetJFSystemToken getJFSystemToken;

    @Autowired
    private HttpSendPostUtil httpSendPostUtil;

    @Autowired
    private CallOut_invoiceQueryOutController callOut_invoiceQueryOutController;

    @Autowired
    private CallOut_invOpenRetInfoOutController callOut_invOpenRetInfoOutController;

    @Autowired
    private CallOut_invPdfOutController callOut_invPdfOutController;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            //检索蓝票表里面的所有电子票（无红冲、无作废的电子票、有票号、已经打印的），返回电子票集合
            List<PInvoiceBlue> eInvoiceList = pInvoiceBlueService.EinvoiceList();
            System.out.println("@@@@@@@@电子票集合数："+eInvoiceList.size());
            //循环取出集合
            for (PInvoiceBlue einvoice : eInvoiceList) {
                //创建请求对象
                String eUrl = null;
                JSONObject RetJsonObject = new JSONObject();
                if (FinalUtil.INVOICE_TYPE_CODE_026.equals(einvoice.getInvoiceTypeCode())) {
                    //获取电子票的url
                    eUrl = callOut_invPdfOutController.invPdfOut(einvoice);

                }
                System.out.println("@@@@@@@@"+eUrl);
                //调用本地数据回调，获取请求数据
                RetJsonObject = callOut_invOpenRetInfoOutController.invOpenRetBlueInfoOut(einvoice, eUrl);
                System.out.println("@@@@@@@@"+RetJsonObject.toString());
                //获取应用接口对应关系列表
                List<IAppInterfaceForm> iAppInterfaceFormsList = getRetUrl("20180117", "160");
                for (IAppInterfaceForm iAppInterfaceForm : iAppInterfaceFormsList) {
                    //调用物业计费系统的接口1005
                    //当要通知物业计费系统的时候，需要制定回调的接口应用
                    if ("1005".equals(iAppInterfaceForm.getInterfaceId())) {
                        /**
                         * 物业计费的接口验证规则
                         * 只接受来自物业的费用
                         */
                        //获取token
                        String token = getJFSystemToken.getJFSystemNewToken("20180117", iAppInterfaceForm.getInterfaceId());
                        //给物业推送消息 如果业务类型里面包含pty则必定是物业费：pty-101支付业务类型:pty-101：物业缴费；pty-102：物业预缴费；
                        //将请求信息推送给物业，并获取响应信息
                        String ret = httpSendPostUtil.sendPost(iAppInterfaceForm.getRequestUrl(), RetJsonObject, token, einvoice.getAppKey(), iAppInterfaceForm.getInterfaceId());
                        System.out.println(ret);
                        logger.info(RetJsonObject);
                        logger.info(iAppInterfaceForm.getRequestUrl());
                        logger.info(ret);
                        com.alibaba.fastjson.JSONObject retObj = JSON.parseObject(ret);
                        String code = retObj.getString("errcode");
                        logger.info("*********" + code);
                        if("0".equals(code))
                        {
                            //保存数据库，更改状态
                            einvoice.setIsPush("1");
                            pInvoiceBlueService.update(einvoice);
                        }else {
                            logger.info("##################################请求信息："+RetJsonObject.toString());
                            logger.info("##################################请求url："+iAppInterfaceForm.getRequestUrl());
                            logger.info("##################################响应信息："+ret);

                        }

                    } else {
                        String result = httpSendPostUtil.sendPost(iAppInterfaceForm.getRequestUrl(), RetJsonObject, einvoice.getAppKey(), iAppInterfaceForm.getInterfaceId());
                        logger.info(RetJsonObject);
                        logger.info(iAppInterfaceForm.getRequestUrl());
                        logger.info(result);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info(e);
        }
    }

    private List<IAppInterfaceForm> getRetUrl(String pAppKey, String pInterfaceId) {
        //============1,根据app_key和interface_id查询出i_app_interface表的guid====
        IAppInterfaceForm iAppInterfaceForm = iAppInterfaceService.getInfoByAppIfKey(pAppKey, pInterfaceId);
        //============3，根据guid，查询i_app_interface_asyn表所有需要回调的系统的returnUrl====
        logger.info("guid" + iAppInterfaceForm.getGuid());
        List<IAppInterfaceForm> iAppInterfaceFormList = iAppInterfaceService.getRetAppInterface(iAppInterfaceForm.getGuid());

        return iAppInterfaceFormList;
    }


}